package jui.maps
{
	import flash.display.LoaderInfo;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.setTimeout;
	
	import jui.business.ManagersFactory;
	import jui.business.XMPPManager;
	import jui.maps.events.JUIEvent;
	
	import modules.webui.WebUIModule;
	
	public class JUIEventMap extends EventDispatcher implements IJUIEventMap 
	{
		private var app: JUI;
		private var xmppManager: XMPPManager;
		
		public function setManagers(): void
		{
			var gm: Function = ManagersFactory.getInstance().getManager;
			xmppManager = gm( XMPPManager.getQName() );
		}
		
		/**
		 * Event Handler for user click on 'Send' Button or Hit Ctrl+Enter
		 */
		public function setHandlers(): void
		{
			app.systemManager.addEventListener(JUIEvent.JUI_SEND_MESSAGE, sendMessageHandler);
			app.systemManager.addEventListener(JUIEvent.JUI_OPEN_URL, openUrlHandler);
		}
		
		//----------------------------------------------------------------------
		// Event Handlers go gere
		//----------------------------------------------------------------------
		
		private function sendMessageHandler(event:JUIEvent): void
		{
			xmppManager.sendMessageTo( event.toJID, event.text );
			
			reloadHTML();
		}
		
		private function openUrlHandler(event:JUIEvent): void
		{
			//var loaderInfo: LoaderInfo = app.webUIModuleLoader.loaderInfo; 
			var webUIModule: WebUIModule = app.webUIModuleLoader.child as WebUIModule;
			webUIModule.gotoAddress(event.text);
			app.appViewStack.selectedIndex = 0;
			
			//reloadHTML();
		}
		
		private function reloadHTML():void
		{
			var webUIModule: WebUIModule = app.webUIModuleLoader.child as WebUIModule; 
			setTimeout(webUIModule.html.reload, 500 );
		}
			
		public function JUIEventMap(target:IEventDispatcher = null, app: JUI = null): void
		{
			if(instance) throw new Error("JUIEventMap is singleton");
			this.app = app;
			setManagers();
			setHandlers();
		}
		
		public static var instance: JUIEventMap;
	}
}